package com.beifu.manager.api.controller.scrap;

import com.beifu.manager.api.common.PageInfo;
import com.beifu.manager.api.domain.scrap.ScrapDetailResponse;
import com.beifu.manager.api.domain.scrap.ScrapListResponse;
import com.beifu.manager.api.domain.scrap.ScrapProduct;
import com.beifu.manager.model.AssetScrap;
import com.beifu.manager.model.AssetScrapDetail;
import com.beifu.manager.service.assetscrap.AssetScrapService;
import com.utils.JsonUtil;
import com.utils.ResponseHelp;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 报废单
 * Created by 再壮 on 2018/6/12.
 */
@RestController
@RequestMapping(value="/mobileserve/scrap/api", produces = "application/json;charset=UTF-8")
public class ScrapController {
    private Map<String, Object> reqMap;
    
    @Autowired
    private AssetScrapService assetScrapService;

    /**
     * 报废单列表
     *  @param reqMap
     * @return
     *
     * 请求报文：
     * {
        "pub":{
            "userId":"222",
            "devID":"",
            "timestamp":""
        },
        "in":{
            "id":"32d我不知道23"
        }

        }
     *   返回数据：
         *卧具报废列表  scrapList
            scrapId	报废单id	char	否
            scrapName	报废单名称	char	否
            status	报废单状态	number	否	1已完成，0未完成

     *
     */
    @RequestMapping(value="/getScrapList", method= RequestMethod.POST)
    public String getScrapList(@RequestBody Map<String, Object> reqMap) {
        // 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));
        // 获取具体值，先这样，
        // TODO 待优化
        // TODO 待增加校验
        String userId = "";
        String devID = "";
        String timestamp = "";
        if (!JSONUtils.isNull(jsonPub)) {
			userId = (String) jsonPub.get("userId");
			devID = (String) jsonPub.get("devID");
			timestamp = (String) jsonPub.get("timestamp");
		}
        
        if(JSONUtils.isNull(jsonIn)){
        	return ResponseHelp.responseApiErrorText("2222", "传入参数不能为空！");
        }
        // 校验
        /*if (null == jsonIn.get("id")) {
            return ResponseHelp.responseApiErrorText("1110", "用户名为空！");
        }*/
        if (null == jsonIn.get("pageIndex")) {
            return ResponseHelp.responseApiErrorText("1111", "pageIndex不能为空！");
        }
        if (null == jsonIn.get("pageNumber")) {
            return ResponseHelp.responseApiErrorText("1112", "pageNumber不能为空！");
        }

//        String id = jsonIn.get("id").toString();
        String pageIndex = jsonIn.get("pageIndex").toString();
        String pageNumber = jsonIn.get("pageNumber").toString();


        List<ScrapListResponse> list = assetScrapService.getScrapList(pageIndex, pageNumber,userId);

        PageInfo pageInfo = new PageInfo();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("assetsOutList", list);
        pageInfo.setResult(map);
        pageInfo.setPageIndex(Integer.valueOf(pageIndex));
        pageInfo.setPageNum(Integer.valueOf(pageNumber));

        return ResponseHelp.responseApiSuccessText(pageInfo);
    }

    /**
     * 报废单详情
     */
    @RequestMapping(value="/getScrapDetail")
    public String getScrapDetail(@RequestBody Map<String, Object> reqMap) {
        // 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));
        // 获取具体值，先这样，
        // TODO 待优化
        String userId = "";
        String devID = "";
        String timestamp = "";
        if (!JSONUtils.isNull(jsonPub)) {
			userId = (String) jsonPub.get("userId");
			devID = (String) jsonPub.get("devID");
			timestamp = (String) jsonPub.get("timestamp");
		}
        
        if(JSONUtils.isNull(jsonIn)){
        	return ResponseHelp.responseApiErrorText("2222", "传入参数不能为空！");
        }
        if (null == jsonIn.get("id")) {
            return ResponseHelp.responseApiErrorText("1111", "报废单ID为空！");
        }
        
        String id = (String) jsonIn.get("id");
        ScrapDetailResponse scrapDetailResponse = assetScrapService.getScrapDetail(id);
        
        return ResponseHelp.responseApiSuccessText(scrapDetailResponse);
    }


    /**
     * 报废单上传
     * @throws ParseException 
     */
    @RequestMapping(value="/scrapListUpload")
    public String uploadScrapDocument(@RequestBody Map<String, Object> reqMap) throws ParseException {
        // 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));
        // 获取具体值，先这样，
        // TODO 待优化
        String userId = "";
        String devID = "";
        String timestamp = "";
        if (!JSONUtils.isNull(jsonPub)) {
			userId = (String) jsonPub.get("userId");
			devID = (String) jsonPub.get("devID");
			timestamp = (String) jsonPub.get("timestamp");
		}
        
        if(JSONUtils.isNull(jsonIn)){
        	return ResponseHelp.responseApiErrorText("2222", "传入参数不能为空！");
        }
        String scrapDesc = (String) jsonIn.get("scrapDesc");//报废描述
        String trainTime = (String) jsonIn.get("trainTime");//执行车次
        List<String> imgs = (List<String>) jsonIn.get("imgs");//报废照片
        String applyDate = (String) jsonIn.get("applyDate");//申请时间
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date createTime = dateFormat.parse(applyDate);
        
        AssetScrap assetScrap = new AssetScrap();
        assetScrap.setCreateUserId(Integer.parseInt(userId));
        assetScrap.setImgList(imgs);
        assetScrap.setCreateTime(createTime);
        assetScrap.setRemark(scrapDesc);
        assetScrap.setTrainNumber(trainTime);

        assetScrap.setStatus("0");//新上传订单状态为0未处理
        
     // 报废单列表参数
        JSONArray jsonArray = (JSONArray) jsonIn.get("scrapList");
        
        //将json数组装换为JavaBean
        List<ScrapProduct> scrapList = new ArrayList<ScrapProduct>();
        if(null != jsonArray && jsonArray.size() > 0){
	        for (Object jsonObject : jsonArray) {
	        	ScrapProduct feedBackParam = JsonUtil.fromJson(jsonObject.toString(), ScrapProduct.class);
	        	scrapList.add(feedBackParam);
			}
        }
        //保存报废单及报废详细信息
        assetScrapService.saveAssetScrap(assetScrap, scrapList, devID);
        return ResponseHelp.responseApiSuccessText(null);
    }

/**
 * 报废单审核上传
 */
    @RequestMapping(value="/scrapApproveUpload")
    public String scrapApproveUpload(@RequestBody Map<String, Object> reqMap) {
        // 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));
        // 获取具体值，先这样，
        // TODO 待优化
        String userId = "";
        String devID = "";
        String timestamp = "";
        if (!JSONUtils.isNull(jsonPub)) {
			userId = (String) jsonPub.get("userId");
			devID = (String) jsonPub.get("devID");
			timestamp = (String) jsonPub.get("timestamp");
		}
        
        if(JSONUtils.isNull(jsonIn)){
        	return ResponseHelp.responseApiErrorText("2222", "传入参数不能为空！");
        }
        String scrapId = (String) jsonIn.get("scrapId");//报废订单
        // 报废单列表参数
        JSONArray jsonArray = (JSONArray) jsonIn.get("scrapList");

        //将json数组装换为JavaBean
        List<ScrapProduct> scrapList = new ArrayList<ScrapProduct>();
        if(null != jsonArray && jsonArray.size() > 0){
	        for (Object jsonObject : jsonArray) {
	        	ScrapProduct feedBackParam = JsonUtil.fromJson(jsonObject.toString(), ScrapProduct.class);
	        	scrapList.add(feedBackParam);
			}
        }else {
            return ResponseHelp.responseApiErrorText("4444", "上传RFID不能为空！");
        }

        //校验审核中的RFID是否和报废单一致
        List<String> RFISList = new ArrayList<String>();//存储RFID
        List<AssetScrapDetail> scrapRFIDList = assetScrapService.getAssetScrapRFIDs(scrapId);
        if(null != scrapRFIDList && scrapRFIDList.size() > 0){
            for (AssetScrapDetail detail : scrapRFIDList) {
                RFISList.add(detail.getAssetInfoRfidCode());
            }
        }else {
            return ResponseHelp.responseApiErrorText("5555", "报废单号输入有误，请重新输入！");
        }
        if(null != scrapList && scrapList.size() > 0){
            for (ScrapProduct product : scrapList) {
                if(!RFISList.contains(product.getRFID())){
                    return ResponseHelp.responseApiErrorText("999", "前端上传不一致，审批失败");
                }
            }
        }

        //更新报废单状态
        assetScrapService.saveAssetScrap(scrapId, scrapList);
        return ResponseHelp.responseApiSuccessText(null);
    }    
    /**
     * 报废单详情
     */
    @RequestMapping(value="/test")
    public String test(@RequestBody Map<String, Object> reqMap) {
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));
        String userId = jsonPub.get("userId").toString();
        String devID = jsonPub.get("devID").toString();
        String timestamp = jsonPub.get("timestamp").toString();
        String id = jsonIn.get("id").toString();

        String responStr = "userId="+userId+",devId="+devID+",timstamp="+timestamp+",id="+id;

        return ResponseHelp.responseApiErrorText("222", responStr);
    }

}
